import { login, logout, getProfileLive } from '@/api/user'

const state = ({
  token: '',
  profileLive: {} // 登陆人信息
})

const getters = {
  token: state => state.token,
  profileLive: state => state.profileLive
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_PROFILELIVE: (state, profileLive) => {
    state.profileLive = profileLive
  }
}

const actions = {
  // 获取会话用户信息
  GetProfileLive({ commit, state }) {
    return new Promise((resolve, reject) => {
      getProfileLive().then((response) => {
        const res = response.data
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 初始化会话用户信息
  SetProfileLive({ commit, state }) {
    return new Promise((resolve, reject) => {
      getProfileLive().then((response) => {
        const res = response.data
        commit('SET_PROFILELIVE', res)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 登录
  Login({ commit, state }, userInfo) {
    const phoneNumber = userInfo.phoneNumber.trim()
    let password = userInfo.password.trim()
    const encrypt = new window.JSEncrypt()
    encrypt.setPublicKey(userInfo.pbky)
    password = encrypt.encrypt(password)
    const pid = userInfo.pid.trim()
    const pky = userInfo.pky.trim()
    return new Promise((resolve, reject) => {
      login({
        phoneNumber,
        password,
        auth_tk: userInfo.auth_tk,
        pbky: userInfo.pbky,
        pid,
        pky
      }).then(response => {
        const data = response.data
        commit('SET_TOKEN', data.bwtk)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 登出
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then((response) => {
        commit('SET_TOKEN', '')
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 设置token
  async SetToken({ commit }, { token }) {
    await commit('SET_TOKEN', token)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
